package com.salesmanager.core.utils;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by Liutong on 9/13/15.
 *
 */
public class AliyunOssUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(AliyunOssUtil.class);

    /**
     *
     * @param client
     * @param bucketName
     * @param key
     * @param file
     */
    public static void createObject(OSSClient client,String bucketName,String key,InputStream file){
        InputStream in = null;
        try {

            //将流写到outputStream 方便获取长度
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int len;
            while ((len = file.read(bytes)) != -1){
                out.write(bytes,0,len);
            }
            in = new ByteArrayInputStream(out.toByteArray());

            ObjectMetadata objectMeta = new ObjectMetadata();
            objectMeta.setContentLength(out.toByteArray().length);
            // 可以在metadata中标记文件类型
            objectMeta.setContentType(TaobaoUtils.getMimeType(out.toByteArray()));

            //计算MD5
            objectMeta.setContentMD5(Base64.encodeToString(TaobaoUtils.encryptMD5(out.toByteArray()), false));

            //上传失败后，重复上传,最多3次
            boolean success;
            for (int i = 0;i<3;i++){

                try {
                    client.putObject(bucketName,key,in,objectMeta);
                    success = true;
                } catch (Exception ex){
                    success = false;
                    LOGGER.error("Put object to oss error,re upload count :"+ (i+1),ex);
                }
                if (success){
                    break;
                }
            }

        }catch (Exception e){
            LOGGER.error(e.getMessage(),e);
        } finally {
            try {
                if (file != null){
                    file.close();
                }
                if (in != null){
                    in.close();
                }
            } catch (IOException e) {
                LOGGER.error("AliyunOssUtil.createObject ERROR:",e);
            }
        }
    }

    /**
     *
     * @param client
     * @param bucketName
     * @param key
     */
    public static void removeObjcet(OSSClient client,String bucketName,String key){
        client.deleteObject(bucketName,key);
    }

    /**
     *
     * @param client
     * @param bucketName
     * @param key
     * @return
     */
    public static OSSObject getObject(OSSClient client,String bucketName,String key){
        return client.getObject(bucketName,key);
    }

}
